<template>
  <div class="mobile-container">
    <!-- 顶部标题栏 -->
    <header class="header">
      <img src="../../assets/images/logo.png" alt="logo" class="logo">
      <div class="title-container">
        <div class="title">西大数信数帮学堂</div>
        <div class="sub-title">广西大学数学与信息科学学院</div>

      </div>
      <div class="search-box">
        <el-input
            v-model="searchKeyword"
            placeholder="输入关键词搜索"
            class="search-input"
            size="small"
            clearable
            @keydown="handleSearchKeydown"
            @keyup.enter="performSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
    </header>

    <!-- 轮播图 -->
    <div class="carousel-wrapper">
      <el-carousel
          ref="carouselRef"
          :interval="5000"
          height="12rem"
          arrow="always"
          indicator-position="none"
          @change="handleCarouselChange"
      >
        <!-- 修改这里：使用 state.value 作为数据源 -->
        <el-carousel-item v-for="(item, index) in state" :key="index">
          <!-- 修改这里：使用 item 对象的属性 -->
          <img :src="getImageUrl(item.bannerId)" :alt="item.title" class="carousel-img"  @click="openSlideUrl(item.url)">
          <div class="carousel-watermark">{{item.title}}</div>
        </el-carousel-item>
      </el-carousel>

      <!-- 如果你想使用真实的轮播数据作为指示器，也需要修改这里 -->
      <div class="carousel-indicators">
    <span
        v-for="(item, index) in state"
        :key="index"
        :class="['indicator-dot', { 'active': currentCarouselIndex === index }]"
        @click="goToSlide(index)"
    ></span>
      </div>
    </div>


    <!-- 课程分类导航 -->
    <div class="course-nav">
      <el-icon class="nav-arrow" @click="scrollNav('left')"><ArrowLeft /></el-icon>
      <div class="nav-items" ref="navScrollRef">
        <div
            v-for="(item, index) in channels"
            :key="index"
            class="nav-item"
            :class="{ 'active': currentNavIndex === index }"
            @click="changeNav(item)"
        >
          <div class="nav-icon" >
            <!--            <span class="icon-emoji">{{ item.icon }}</span>-->
            <img :src="getImageUrl(item.iconName)" class="nav-icon-img"  >
          </div>
          <span class="nav-label">{{ item.channelName }}</span>
        </div>
      </div>
      <el-icon class="nav-arrow" @click="scrollNav('right')"><ArrowRight /></el-icon>
    </div>

    <!-- 热力排行 -->
    <section class="content-section">
      <div class="section-header">
        <h2 class="section-title">热力排行</h2>
        <button class="more-btn" @click="router.push('/mobileSearch?kw=&sort=PLAY')">更多<el-icon><ArrowRight /></el-icon></button>
      </div>
      <div class="rank-grid">
        <div
            v-for="(item, index) in hotRankLists?.records || []"
            :key="index"
            class="rank-card"
            @click="goToVideo(item)"
        >
          <div class="video-cover">
            <img :src="getImageUrl(item.bannerId)" :alt="item.title" loading="lazy">
            <div class="video-duration">{{ displayDuration(item?.duration ?? 0*1000) }}</div>
            <div class="play-icon">▶</div>
          </div>
          <div class="video-info">
            <p class="video-title">{{ item.title }}</p>
            <div class="video-meta">
              <span><el-icon><VideoPlay /></el-icon>{{ item.plays }}</span>
<!--              <span><el-icon><ChatDotRound /></el-icon>{{ item.commentCount }}</span>-->
            </div>
            <div class="author-info">
              <img :src="getImageUrl(item.user.avatarId)" :alt="item.user.nickname" class="avatar">
              <span class="author-name">{{ item.user.nickname }}</span>
              <span class="publish-date">{{ item.dynamic.publishTimeStr  }}</span>
            </div>
          </div>
        </div>
      </div>
    </section>

    <!-- 合集列表 -->
    <section class="content-section">
      <div class="section-header">
        <h2 class="section-title">合集列表</h2>
        <button class="more-btn" @click="router.push('/mobileSearch?kw=&sort=TIME')">更多<el-icon><ArrowRight /></el-icon></button>
      </div>
      <div class="collection-list">
        <div
            v-for="(item, index) in newLists?.records || []"
            :key="index"
            class="collection-card"
            @click="goToVideo(item)"
        >
          <div class="collection-cover">
            <img :src="getImageUrl(item.bannerId)" :alt="item.title" loading="lazy">
            <div class="video-duration">{{ displayDuration(item?.duration ?? 0*1000) }}</div>
          </div>
          <div class="collection-info">
            <p class="collection-title">{{ item.title }}</p>
            <div class="collection-meta">
              <span class="up-tag">UP</span>
              <span class="author">{{ item.user.nickname }}</span>
            </div>
            <div class="collection-stats">
              <span><el-icon><VideoPlay /></el-icon>{{ item.plays }}</span>
<!--              <span><el-icon><ChatDotRound /></el-icon>{{ item.commentCount }}</span>-->
            </div>
          </div>
        </div>
      </div>
    </section>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { Search, ArrowLeft, ArrowRight, VideoPlay, ChatDotRound } from '@element-plus/icons-vue'
import { listCarousels } from '@/apis/system';
import { imageUrl } from '@/apis/image';
import { listVideoChannels } from '@/apis/video/channel';
import videoApi from '@/apis/video';
import {displayDuration} from "@/utils/common.ts";


const { state, isLoading, isReady } = useAsyncState(listCarousels({ position: 'HOME'}), null)
const { state: channels } = useAsyncState(listVideoChannels({
  child: true
}), [])

const router = useRouter()
const route = useRoute()

// 搜索关键词
const searchKeyword = ref('')
const tipIndex = ref(-1)
const tipList = ref([])
const currentSlideIndex = ref(0);


// 添加键盘事件处理
function handleSearchKeydown(e: KeyboardEvent) {
  let offset = 0
  if (e.code === 'ArrowUp') {
    offset = -1
  } else if (e.code === 'ArrowDown') {
    offset = 1
  }

  if (offset) {
    e.preventDefault()
    const newIndex = tipIndex.value + offset
    if (newIndex >= tipList.value.length) {
      tipIndex.value = -1
    } else if(newIndex < -1) {
      tipIndex.value = tipList.value.length - 1
    } else {
      tipIndex.value = newIndex
    }
  }
}

// 执行搜索功能
function performSearch() {
  console.log('测试的辞keyword:', searchKeyword.value)
  // 检查是否已经在mobileSearch页面并且参数相同
  if (route.name === 'mobileSearch' && route.query.kw === searchKeyword.value) {
    console.log('Already on the same search page with same query')
    return
  }

  // 在这里添加实际的搜索逻辑
  router.push(`/mobileSearch?kw=${encodeURIComponent(searchKeyword.value)}`)
}

function openSlideUrl(url: string) {
  if ( url) {
    window.open(url, '_blank')
  } else {
    console.warn('当前幻灯片没有URL')
  }
}

// 添加时间记录
const courseTimes = ref<Record<string, number>>({})

//点击视频
const  goToVideo = (value: Object) => {

  const url = generateVideoUrl(value)
  // 使用 Vue Router 在当前页面跳转
  router.push(url)
}
// 生成视频链接
const generateVideoUrl = (course: object) => {
  let url = '/mobile/play/' + course.sid
  const currentTime = courseTimes.value[course.sid] || 0

  if (currentTime >= 3) {
    url += '#time' + currentTime
  }
  return url
}

const currentSlide = computed(() => {
  if (!state.value || state.value.length === 0) {
    return {
      bannerId: '',
      title: ''
    }
  }
  return state.value[currentSlideIndex.value]
})



// 获取图片URL
function getImageUrl(bannerId: string) {
  // 根据您的实际API调整图片URL构造方式
  // return `/api/resource/${bannerId}`
  return imageUrl + bannerId
}


// 轮播图数据
const currentCarouselIndex = ref(0)
const carouselRef = ref()


const handleCarouselChange = (index: number) => {
  currentCarouselIndex.value = index
}

const goToSlide = (index: number) => {
  if (carouselRef.value) {
    carouselRef.value.setActiveItem(index)
  }
}

// 课程分类导航数据
const currentNavIndex = ref(2) // 默认选中"高等代数"
const navScrollRef = ref<HTMLElement>()


const changeNav = (item: object) => {
  // 可以在这里触发分类筛选
  console.log('Selected category:', item)
  // 使用 Vue Router 在当前页面跳转
  router.push("/mobile/channel/"+item.id);
}

const scrollNav = (direction: 'left' | 'right') => {
  if (!navScrollRef.value) return
  const scrollAmount = 200
  navScrollRef.value.scrollBy({
    left: direction === 'left' ? -scrollAmount : scrollAmount,
    behavior: 'smooth'
  })
}

const params = ref({
  pageNum: 1,
  pageSize: 6,
  type: 'VIDEO',
  keyword: '',
  sort: 'PLAY'
})

const { state: hotRankLists } = useAsyncState(videoApi.search(params.value), null)

//最新发布
const newparams = ref({
  pageNum: 1,
  pageSize: 6,
  type: 'VIDEO',
  keyword: '',
  sort: 'TIME'
})
const { state: newLists } = useAsyncState(videoApi.search(newparams.value), null)
// 热力排行数据


</script>

<style scoped lang="scss">

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

img {
  max-width: 100%;
  height: auto;
  display: block;
}

:global(html) {
  overflow-x: hidden;
  width: 100%;
}

:global(body) {
  overflow-x: hidden;
  width: 100%;
  margin: 0;
  padding: 0;
}

.mobile-container {
  height: calc(100vh - 90px);
  background-color: #f5f5f5;
  -webkit-tap-highlight-color: transparent;
  font-family: "Microsoft Yahei", "Heiti SC", sans-serif;
  overflow-x: hidden;
  width: 100%;
  max-width: 100%;
  position: relative;

  & > * {
    max-width: 100%;
  }
}

// 头部样式
.header {
  display: flex;
  align-items: center;
  background: linear-gradient(to bottom, rgba(255, 255, 255, 0.2), rgba(255, 255, 255, 0.2)),
  url('@/assets/images/home_banner/1sz3p8w2Sk.png@3840w_400h_1c.webp');
  background-size: cover;
  background-position: center;
  backdrop-filter: blur(2px);
  padding: 6px 10px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.06);
  position: sticky;
  top: 0;
  z-index: 999;
  gap: 6px;
  width: 100%;
  box-sizing: border-box;

  .logo {
    width: 32px;
    height: 32px;
    min-width: 32px;
    border-radius: 3px;
    flex-shrink: 0;
    object-fit: cover;
  }

  .title-container {
    flex: 1;
    min-width: 0;

    .title {
      font-size: 13px;
      font-weight: 600;
      line-height: 1.1;
      color: #222;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      margin-bottom: 1px;
    }

    .sub-title {
      font-size: 8px;
      color: #888;
      line-height: 1.1;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }

  .search-box {
    flex: 0 0 180px;
    display: flex;
    align-items: center;
    justify-content: flex-end;

    .search-input {
      width: 100%;

      :deep(.el-input__wrapper) {
        border-radius: 15px;
        background-color: #ffffff;
        box-shadow: none;
        padding: 2px 8px;
        min-height: 26px;
      }

      :deep(.el-input__inner) {
        font-size: 10px;
        color: #666;

        &::placeholder {
          color: #999;
        }
      }

      :deep(.el-input__prefix) {
        color: #999;
        font-size: 11px;
        margin-right: 4px;
      }
    }
  }
}

// 轮播图样式
.carousel-wrapper {
  position: relative;
  margin: 10px 0;
  padding: 0 15px;
  box-sizing: border-box;
  width: 100%;

  :deep(.el-carousel) {
    border-radius: 10px;
    overflow: hidden;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  }

  .carousel-img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  .carousel-watermark {
    position: absolute;
    bottom: 10px;
    left: 27px;
    color: #fff;
    font-size: 12px;
    z-index: 10;
    display: flex;
    align-items: center;
    gap: 4px;
    text-shadow: 0 1px 3px rgba(0, 0, 0, 0.5);

    &::before {
      content: '';
      width: 6px;
      height: 6px;
      border-radius: 50%;
      background-color: #fff;
    }
  }

  .carousel-indicators {
    position: absolute;
    bottom: 10px;
    left: 50%;
    transform: translateX(-50%);
    display: flex;
    gap: 8px;
    z-index: 10;
    margin-left: 0;

    .indicator-dot {
      width: 6px;
      height: 6px;
      border-radius: 50%;
      background-color: rgba(255, 255, 255, 0.5);
      cursor: pointer;
      transition: all 0.3s ease;

      &.active {
        width: 20px;
        border-radius: 3px;
        background-color: #fff;
      }

      &:hover {
        background-color: rgba(255, 255, 255, 0.8);
      }
    }
  }

  :deep(.el-carousel__arrow) {
    width: 36px;
    height: 36px;
    background-color: rgba(0, 0, 0, 0.3);

    &:hover {
      background-color: rgba(0, 0, 0, 0.5);
    }

    &.el-carousel__arrow--left {
      left: 10px;
    }

    &.el-carousel__arrow--right {
      right: 10px;
    }
  }
}

// 课程导航
.course-nav {
  display: flex;
  align-items: center;
  background-color: #fff;
  padding: 15px 8px;
  gap: 8px;
  margin-top: 0;
  width: 100%;
  box-sizing: border-box;

  .nav-arrow {
    flex-shrink: 0;
    font-size: 18px;
    color: #bbb;
    cursor: pointer;
    padding: 4px;
    transition: color 0.3s ease;

    &:hover {
      color: #666;
    }
  }

  .nav-items {
    flex: 1;
    display: flex;
    overflow-x: auto;
    scroll-behavior: smooth;
    gap: 10px;
    padding: 5px 0;
    min-width: 0;

    &::-webkit-scrollbar {
      display: none;
    }

    .nav-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      min-width: 52px;
      max-width: 52px;
      cursor: pointer;
      flex-shrink: 0;
      transition: all 0.3s ease;
      // 设置固定高度以便计算比例
      height: 60px;

      .nav-icon {
        // 占据2/3高度 (60px * 2/3 = 40px)
        width: 75%;
        height: 75%;
        // 圆角图标样式
        border-radius: 10px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-bottom: 4px;
        transition: transform 0.3s ease;
        overflow: hidden;

        .icon-emoji {
          font-size: 22px;
        }

        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
          // 保持圆角效果
          border-radius: 8px;
        }
      }

      .nav-label {
        font-size: 11px;
        color: #333;
        white-space: nowrap;
        transition: all 0.3s ease;
        overflow: hidden;
        text-overflow: ellipsis;
        max-width: 100%;
        // 占据1/3高度 (60px * 1/3 = 20px)
        height: 20px;
        line-height: 20px;
      }

      &:hover {
        .nav-icon {
          transform: scale(1.05);
        }
      }

      &.active {
        .nav-label {
          color: #FF6B35;
          font-weight: 500;
          position: relative;

          &::after {
            content: '';
            position: absolute;
            bottom: -3px;
            left: 50%;
            transform: translateX(-50%);
            width: 20px;
            height: 2.5px;
            background-color: #FF6B35;
            border-radius: 1.5px;
          }
        }
      }
    }
  }
}


// 内容区域
.content-section {
  background-color: #fff;
  padding: 12px 16px;
  margin: 8px 0;
  width: 100%;
  box-sizing: border-box;

  &:first-of-type {
    margin-top: 0;
  }

  &:last-of-type {
    margin-bottom: 0;
  }

  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
    width: 100%;

    .section-title {
      font-size: 16px;
      font-weight: 600;
      color: #333;
    }

    .more-btn {
      display: flex;
      align-items: center;
      gap: 4px;
      padding: 4px 8px;
      font-size: 13px;
      color: #999;
      background: none;
      border: none;
      cursor: pointer;
      transition: color 0.3s ease;

      &:hover {
        color: #409eff;
      }
    }
  }
}

// 热力排行
.rank-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 8px;
  width: 100%;

  .rank-card {
    background-color: #fff;
    border-radius: 8px;
    overflow: hidden;
    cursor: pointer;
    transition: transform 0.2s ease, box-shadow 0.2s ease;
    width: 100%;
    max-width: 100%;

    &:hover {
      transform: translateY(-4px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }

    .video-cover {
      position: relative;
      width: 100%;
      padding-bottom: 56.25%;
      overflow: hidden;
      background-color: #f0f0f0;

      img {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        object-fit: cover;
      }

      .video-duration {
        position: absolute;
        bottom: 6px;
        right: 6px;
        background-color: rgba(0, 0, 0, 0.7);
        color: #fff;
        padding: 2px 6px;
        border-radius: 3px;
        font-size: 11px;
        z-index: 2;
      }

      .play-icon {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        width: 32px;
        height: 32px;
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: rgba(0, 0, 0, 0.5);
        border-radius: 50%;
        color: #fff;
        font-size: 14px;
        opacity: 0;
        transition: opacity 0.3s ease;
      }

      &:hover .play-icon {
        opacity: 1;
      }
    }

    .video-info {
      padding: 8px;

      .video-title {
        font-size: 12px;
        line-height: 1.4;
        color: #333;
        margin-bottom: 8px;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
      }

      .video-meta {
        display: flex;
        gap: 12px;
        font-size: 11px;
        color: #999;
        margin-bottom: 8px;

        span {
          display: flex;
          align-items: center;
          gap: 4px;
        }
      }

      .author-info {
        display: flex;
        align-items: center;
        gap: 6px;
        font-size: 11px;
        color: #666;

        .avatar {
          width: 16px;
          height: 16px;
          border-radius: 50%;
        }

        .author-name {
          flex: 1;
        }

        .publish-date {
          color: #999;
        }
      }
    }
  }
}

// 合集列表
.collection-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
  width: 100%;

  .collection-card {
    display: flex;
    background-color: #fff;
    border-radius: 8px;
    overflow: hidden;
    cursor: pointer;
    transition: transform 0.2s ease;
    width: 100%;
    max-width: 100%;
    height: 13vh;

    &:hover {
      transform: translateX(4px);
    }

    .collection-cover {
      position: relative;
      width: 40%;
      flex-shrink: 0;
      background-color: #f0f0f0;

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }

      .video-duration {
        position: absolute;
        bottom: 6px;
        right: 6px;
        background-color: rgba(0, 0, 0, 0.7);
        color: #fff;
        padding: 2px 6px;
        border-radius: 3px;
        font-size: 11px;
      }
    }

    .collection-info {
      flex: 1;
      padding: 12px;
      display: flex;
      flex-direction: column;
      justify-content: space-between;

      .collection-title {
        font-size: 13px;
        line-height: 1.5;
        color: #333;
        margin-bottom: 8px;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
      }

      .collection-meta {
        display: flex;
        align-items: center;
        gap: 8px;
        font-size: 11px;
        margin-bottom: 8px;

        .up-tag {
          background-color: #e8f4ff;
          color: #409eff;
          padding: 2px 6px;
          border-radius: 3px;
          font-weight: 500;
        }

        .author {
          color: #666;
        }
      }

      .collection-stats {
        display: flex;
        gap: 12px;
        font-size: 11px;
        color: #999;

        span {
          display: flex;
          align-items: center;
          gap: 4px;
        }
      }
    }
  }
}

// 响应式适配
@media (max-width: 768px) {
  .rank-grid {
    grid-template-columns: repeat(3, 1fr);
    gap: 8px;
  }
}

@media (max-width: 480px) {
  .header {
    .search-input {
      width: 100px;
    }
  }

  .rank-grid {
    .rank-card .video-info {
      .video-title {
        font-size: 11px;
      }
    }
  }
}
</style>
